package org.example.service;

import org.example.entity.JobPost;
import org.example.entity.User;
import org.example.entity.UserType;
import org.example.repository.JobPostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

@Service
public class JobService {
    @Autowired
    private JobPostRepository jobPostRepository;

    @Autowired
    private UserService userService;

    @Transactional
    public JobPost createJobPost(Long userId, JobPost jobPost) {
        User publisher = userService.getUser(userId);

        if (publisher.isBlocked()) {
            throw new RuntimeException("用户已被封禁");
        }

        if (publisher.getUserType() == UserType.ENTERPRISE) {
            checkPostLimit(publisher);
        }

        jobPost.setPublisher(publisher);
        return jobPostRepository.save(jobPost);
    }

    private void checkPostLimit(User user) {
        if (!user.isMember()) {

            LocalDate localDate = LocalDate.now();
            Date currentDate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

            // 检查 lastActionDate 是否在当前日期之前
            if (user.getLastActionDate().before(currentDate)) {
                user.setDailyPostCount(0);
                user.setLastActionDate(currentDate);
            }

            if (user.getDailyPostCount() >= 3) {
                throw new RuntimeException("非会员企业每日最多发布3个岗位");
            }

            user.setDailyPostCount(user.getDailyPostCount() + 1);
            userService.save(user);
        }
    }
}
